<template>
  <div class="addExamBox">
    <el-dialog
      title="查看详情"
      :visible.sync="examDetailShow"
      :fullscreen="true">
      <div class="body-box">
        <div class='top'>
          <el-form :inline="true">
            <el-form-item label="时间段">
              <el-select v-model="chooseDateId" placeholder="选择时间段" style="width: 240px" size="small">
                <el-option
                  v-for="item in examRecordsDates"
                  :key="item.id"
                  :label="item.itemBak"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="small" icon="el-icon-delete">清空</el-button>
              <el-button size="small" type="primary" icon="el-icon-search" @click="getList()">搜索</el-button>
            </el-form-item>
          </el-form>
          
        </div>
        <div class='middle'>
          <ag-grid-vue 
            class="ag-theme-alpine ag-theme-quartz" 
            style='height: 100% !important;'
            :gridOptions="gridOptions" 
            :localeText="localeText"
            @grid-ready="onGridReady"
            :rowHeight="38" 
            :headerHeight="42" 
            :columnDefs="columnDefs" 
            :defaultColDef="defaultColDef"
            :rowData="rowData" 
            rowSelection="multiple" 
            :rowMultiSelectWithClick="true"
            :enableRangeSelection="true">
          </ag-grid-vue>
        </div>
        <div class='bottom'>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="page.currentPage" :page-sizes="page.pageSizes" :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="page.total">
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { recordsDetail, examResultPageDate } from '@/api/examTest.js'
export default {
  props: ['password'],
  data () {
    return {
      examDetailShow: false,
      examId: '',
      chooseDateId: '',
      examRecordsDates: [],
      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      gridOptions: null,
      localeText: this.$AG_GRID_LOCALE_ZZZ,
      columnDefs: [],
      col: [],
      rowData: null,
      defaultColDef: {
        editable: false,
        sortable: true,
        resizable: true,
        filter: true,
        cellDataType: false
      },
      rowIndexArr: [
        {
          field: 'rowIndex',
          headerName: '序号',
          width: 70,
          checkboxSelection: false,
          headerCheckboxSelection: false,
          sortable: false,
          pinned: 'left',
          valueGetter: (params) => {
            // 返回当前行的序号
            return params.node.rowIndex + 1
          }
        },
        {
          headerName: '姓名',
          field: 'studentName',
          filter: 'studentName',
          tooltipField: 'studentName',
          width: 120,
          id: 103,
          sortable: true,
          resizable: true,
          hide: false,
          editable: false,
          tooltipComponentParams: {
            'color': '#55AA77'
          },
          pinned: 'left'
        },
        {
          headerName: '使用考站数',
          field: 'stationsCount',
          filter: 'stationsCount',
          tooltipField: 'stationsCount',
          width: 120,
          id: 103,
          sortable: true,
          resizable: true,
          hide: false,
          editable: false,
          tooltipComponentParams: {
            'color': '#55AA77'
          }
        }
      ]
    }
  },
  beforeMount () {
    this.gridOptions = {
      // 通过这个属性建立了上下文引用
      context: { componentParent: this }
      // 说人话就是可以在自己声明的组件里调用到父组件的方法和属性了
    }
  },
  methods: {
    closeHandle () {
      this.examDetailShow = false
    },
    getDetail (val) {
      this.examDetailShow = true
      this.examId = val.id
      setTimeout(() => {
        this.getDateDetail()
      }, 10)
    },
    // 获取时间段详情
    getDateDetail () {
      let params = {
        id: this.examId
      }
      if (this.password !== null) {
        params.password = this.password
        params.passwordType = 1
      }
      recordsDetail(params).then(res => {
        let aaa = JSON.parse(JSON.stringify(res.data.examRecordsDtos[0].examRecordsDates))
        let aaabbb = aaa.sort((a, b) => parseInt(new Date(`${a.examStartDate}`).getTime()) - parseInt(new Date(`${b.examStartDate}`).getTime()))
        aaabbb.map(q => {
          q.itemBak = `${q.examStartDate.substring(0, 16)} ~ ${q.examEndDate.substring(10, 16)}`
        })
        this.examRecordsDates = JSON.parse(JSON.stringify(aaabbb))
        this.chooseDateId = this.examRecordsDates[0].id

        this.getList()
      })
    },
    // 选择时间段
    chooseDateHandle (val) {
      if (this.chooseDateId !== val.id) {
        this.chooseDateId = val.id
      }
    },
    // 装载列表
    onGridReady (params) {
      this.gridApi = params.api
    },
    // onSortChangedAggrid (event) {
    //   const api = event.api
    //   const visibleRowCount = api.getDisplayedRowCount()
    //   for (let i = 0; i < visibleRowCount; i++) {
    //     const rowNode = api.getDisplayedRowAtIndex(i)
    //     console.log(rowNode)
    //   }
    //   let aaa = JSON.parse(JSON.stringify(this.rowData))
    //   if (this.gridApi.getRenderedNodes().length > 1) {
    //     this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
    //   } else {
    //     this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
    //   }
    //   setTimeout(() => {
    //     this.rowData = JSON.parse(JSON.stringify(aaa))
    //     setTimeout(() => {
    //       if (this.aggridScrollNum !== 0) {
    //         this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
    //       }
    //     }, 10)
    //   }, 10)
    // },
    // onFilterChangedAggrid (event) {
    //   const api = event.api
    //   const visibleRowCount = api.getDisplayedRowCount()
    //   for (let i = 0; i < visibleRowCount; i++) {
    //     const rowNode = api.getDisplayedRowAtIndex(i)
    //     console.log(rowNode)
    //   }
    //   let aaa = JSON.parse(JSON.stringify(this.rowData))
    //   if (this.gridApi.getRenderedNodes().length > 1) {
    //     this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
    //   } else {
    //     this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
    //   }
    //   setTimeout(() => {
    //     this.rowData = JSON.parse(JSON.stringify(aaa))
    //     setTimeout(() => {
    //       if (this.aggridScrollNum !== 0) {
    //         this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
    //       }
    //     }, 10)
    //   }, 10)
    // },
    // 获取表头
    getHeadersCol () {
      this.columnDefs = []
      setTimeout(() => {
        this.columnDefs = this.rowIndexArr
      }, 10)
    },
    getList () {
      let params = {
        recordsId: this.examId,
        recordsDateId: this.chooseDateId,
        page: this.page.currentPage,
        limit: this.page.pageSize
      }
      examResultPageDate(params).then(res => {
        let students = res.data.page.records
        // console.log(students, 222)
        let arr = []
        students.map(v => {
          let bbb = JSON.parse(JSON.stringify(v))
          bbb.stationsCount = this.countProperties(bbb.stations)
          let arrs = []
          // bbb.stations.map(qq => { })
          for (var el in bbb.stations) {
            arrs.push({
              name: el,
              teachers: bbb.stations[el]
            })
          }
          arrs = arrs.sort((a, b) => parseInt(a.name.substring(1, 2)) - parseInt(b.name.substring(1, 2)))
          bbb.stationsObj = arrs
          arr.push(bbb)
        })

        if (arr.length > 0) {
          let firstStudent = arr[0]
          let aaa = []
          firstStudent.stationsObj.map(q => {
            console.log(q)
            q.teachers.map((p, index) => {
              aaa.push({
                headerName: q.name + '考官' + Number(index + 1) + '姓名',
                field: q.name + 'teacher' + Number(index + 1),
                filter: q.name + 'teacher' + Number(index + 1),
                tooltipField: q.name + 'teacher' + Number(index + 1),
                minWidth: 160,
                flex: 1,
                sortable: true,
                resizable: true,
                hide: false,
                editable: false
              })
              aaa.push({
                headerName: q.name + '考官' + Number(index + 1) + '得分',
                field: q.name + 'result' + Number(index + 1),
                filter: q.name + 'result' + Number(index + 1),
                tooltipField: q.name + 'result' + Number(index + 1),
                minWidth: 160,
                flex: 1,
                sortable: true,
                resizable: true,
                hide: false,
                editable: false
              })
            })
            aaa.push({
              headerName: q.name + '得分',
              field: q.name + 'score',
              filter: q.name + 'score',
              tooltipField: q.name + 'score',
              minWidth: 120,
              flex: 1,
              sortable: true,
              resizable: true,
              hide: false,
              editable: false
            })
          })
          aaa.push({
            headerName: '总得分',
            field: 'allScore',
            filter: 'allScore',
            tooltipField: 'allScore',
            width: 120,
            sortable: true,
            resizable: true,
            hide: false,
            editable: false,
            pinned: 'right'
          })
          arr.map(pq => {
            let allScore = 0
            pq.stationsObj.map(q => {
              let score = 0
              let k = 0
              q.teachers.map((p) => {
                if (p.result >= 0) {
                  score += Number(p.result)
                }
                k++
              })
              score = (score / k).toFixed(2)
              q.teachers.map((p, index) => {
                // name
                let key1 = q.name + 'teacher' + Number(index + 1)
                // result
                let key2 = q.name + 'result' + Number(index + 1)
                // score
                let key3 = q.name + 'score'
                pq[key1] = p.teacherName || '暂无'
                pq[key2] = p.result < 0 ? '暂无' : p.result
                pq[key3] = score < 0 ? '暂无' : score
              })
              allScore += Number(score)
              pq.allScore = Number(allScore).toFixed(2)
              if (pq.allScore < 0 || String(pq.allScore) === 'NaN') {
                pq.allScore = '暂无'
              }
            })
          })
          // 获取表头
          this.columnDefs = []
          this.columnDefs = this.rowIndexArr.concat(aaa)
          this.rowData = []
          this.rowData = JSON.parse(JSON.stringify(arr))
          console.log(this.rowData)
          this.page.total = res.data.page.total
        } else {
          this.columnDefs = this.rowIndexArr.concat([])
          this.rowData = []
          this.rowData = JSON.parse(JSON.stringify(arr))
          console.log(this.rowData)
          this.page.total = 0
        }
      })
    },
    // 判断对象几个属性
    countProperties (obj) {
      return Object.keys(obj).length
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getList()
    }
  }
}
</script>

<style lang='scss'>
.el-table .warning-row {
  background: #00b99e10;
}

.el-table .success-row {
  background: #ebf2f940;
}
.custom-table {
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #00b99e50;
  box-shadow: 0 0 5px #00b99e80;
}
/* 设置表头高度 */
.custom-table .el-table__header-wrapper .el-table__header {
  height: 20px !important; /* 你想要的高度 */
}
.custom-table thead .el-table__cell{
  height: 20px !important; /* 你想要的高度 */
  line-height: 20px !important; /* 你想要的高度 */
  background: #eeeeee;
  
}
.addExamBox{
  .el-dialog__body{
    height: calc( 100vh - 47px );
    margin: 0;
    padding: 0;
    .body-box{
      height: calc( 100vh - 47px );
      margin: 0;
      padding: 0;
      flex-direction: column;
      overflow: auto;
      display: flex;
      flex-direction: column;
      .top{
        width: 100%;
        padding: 20px 10px 0;
      }
      .middle{
        width: 100%;
        padding: 10px;
        flex: 1;
        // .ag-theme-alpine{
        //   height: 100%;
        // }
      }
      .bottom{
        width: 100%;
        padding: 10px 10px 10px;
      }
    }
  }
  .ag-body-viewport [col-id='第1考站teacher1'],
  .ag-body-viewport [col-id='第1考站result1'],
  .ag-body-viewport [col-id='第1考站teacher2'],
  .ag-body-viewport [col-id='第1考站result2'],
  .ag-body-viewport [col-id='第1考站teacher3'],
  .ag-body-viewport [col-id='第1考站result3'],
  .ag-body-viewport [col-id='第3考站teacher1'],
  .ag-body-viewport [col-id='第3考站result1'],
  .ag-body-viewport [col-id='第3考站teacher2'],
  .ag-body-viewport [col-id='第3考站result2'],
  .ag-body-viewport [col-id='第3考站teacher3'],
  .ag-body-viewport [col-id='第3考站result3'],
  .ag-body-viewport [col-id='第5考站teacher1'],
  .ag-body-viewport [col-id='第5考站result1'],
  .ag-body-viewport [col-id='第5考站teacher2'],
  .ag-body-viewport [col-id='第5考站result2'],
  .ag-body-viewport [col-id='第5考站teacher3'],
  .ag-body-viewport [col-id='第5考站result3'],
  .ag-body-viewport [col-id='第7考站teacher1'],
  .ag-body-viewport [col-id='第7考站result1'],
  .ag-body-viewport [col-id='第7考站teacher2'],
  .ag-body-viewport [col-id='第7考站result2'],
  .ag-body-viewport [col-id='第7考站teacher3'],
  .ag-body-viewport [col-id='第7考站result3'],
  .ag-body-viewport [col-id='第9考站teacher1'],
  .ag-body-viewport [col-id='第9考站result1'],
  .ag-body-viewport [col-id='第9考站teacher2'],
  .ag-body-viewport [col-id='第9考站result2'],
  .ag-body-viewport [col-id='第9考站teacher3'],
  .ag-body-viewport [col-id='第9考站result3'] {
    background-color: rgba(243,229,219,0.3);
  }
  .ag-body-viewport [col-id='第1考站score'], 
  .ag-body-viewport [col-id='第3考站score'],
  .ag-body-viewport [col-id='第5考站score'],
  .ag-body-viewport [col-id='第7考站score'],
  .ag-body-viewport [col-id='第9考站score'] {
    background-color: rgba(243,229,219,0.8);;
  }
  .ag-body-viewport [col-id='第2考站teacher1'],
  .ag-body-viewport [col-id='第2考站result1'],
  .ag-body-viewport [col-id='第2考站teacher2'],
  .ag-body-viewport [col-id='第2考站result2'],
  .ag-body-viewport [col-id='第2考站teacher3'],
  .ag-body-viewport [col-id='第2考站result3'],
  .ag-body-viewport [col-id='第4考站teacher1'],
  .ag-body-viewport [col-id='第4考站result1'],
  .ag-body-viewport [col-id='第4考站teacher2'],
  .ag-body-viewport [col-id='第4考站result2'],
  .ag-body-viewport [col-id='第4考站teacher3'],
  .ag-body-viewport [col-id='第4考站result3'],
  .ag-body-viewport [col-id='第6考站teacher1'],
  .ag-body-viewport [col-id='第6考站result1'],
  .ag-body-viewport [col-id='第6考站teacher2'],
  .ag-body-viewport [col-id='第6考站result2'],
  .ag-body-viewport [col-id='第6考站teacher3'],
  .ag-body-viewport [col-id='第6考站result3'],
  .ag-body-viewport [col-id='第8考站teacher1'],
  .ag-body-viewport [col-id='第8考站result1'],
  .ag-body-viewport [col-id='第8考站teacher2'],
  .ag-body-viewport [col-id='第8考站result2'],
  .ag-body-viewport [col-id='第8考站teacher3'],
  .ag-body-viewport [col-id='第10考站result3'],
  .ag-body-viewport [col-id='第10考站teacher1'],
  .ag-body-viewport [col-id='第10考站result1'],
  .ag-body-viewport [col-id='第10考站teacher2'],
  .ag-body-viewport [col-id='第10考站result2'],
  .ag-body-viewport [col-id='第10考站teacher3'],
  .ag-body-viewport [col-id='第10考站result3'] {
    background-color: rgba(70,171,217,0.3);
  }
  .ag-body-viewport [col-id='第2考站score'],
  .ag-body-viewport [col-id='第4考站score'],
  .ag-body-viewport [col-id='第6考站score'],
  .ag-body-viewport [col-id='第8考站score'],
  .ag-body-viewport [col-id='第10考站score'] {
    background-color: rgba(70,171,217,0.8);
  }
  .ag-body-viewport [col-id='allScore'] {
    background-color: rgba(178, 233, 219, 0.99);
    font-weight: 600;
  }

}

</style>